<template>
  <BasicModal width="800px" @register="register"
              title="编辑" @ok.stop="handleSubmit">
    <BasicForm @register="registerForm">
      <template #pwd="{ model, field }">
        <a-row :gutter="8">
          <a-col :sm="15" :md="16" :lg="17" :xl="19">
            <a-input-password v-model:value="model[field]" placeholder="请输入密码" />
          </a-col>
          <a-col :sm="9" :md="7" :lg="7" :xl="5">
            <a-button type="primary" style="width: 100%" @click="handleTest">测试</a-button>
          </a-col>
        </a-row>
      </template>

      <template #dataSourceType="{model, field, schema}">
        <DictSelect dict-code="database_type" v-bind="schema" allowClear
                    v-model:value="model[field]" placeholder="请选择数据库类型"
                    v-model:title="model.dataSourceTypeName" />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script setup>
import { BasicModal, useModal } from "@/components/Modal";
import { BasicForm, useForm } from "@/components/Form";
import DictSelect from "@/components/DictSelect/DictSelect.vue";
import { testConnection } from "@/views/monitor/datasource/datasource.api";
import { nextTick } from "vue";
import { defHttp } from "@/utils/http/axios";

const emits = defineEmits(["ok"]);
defineOptions({ name: "DataSourceModal" });
const [register, { closeModal, openModal, setModalProps }] = useModal();
const dbDriverMap = {
  // MySQL 数据库
  "1": { driverClass: "com.mysql.jdbc.Driver" },
  //MySQL5.7+ 数据库
  "4": { driverClass: "com.mysql.cj.jdbc.Driver" },
  // Oracle
  "2": { driverClass: "oracle.jdbc.OracleDriver" },
  // SQLServer 数据库
  "3": { driverClass: "com.microsoft.sqlserver.jdbc.SQLServerDriver" },
  // marialDB 数据库
  "5": { driverClass: "org.mariadb.jdbc.Driver" },
  // postgresql 数据库
  "6": { driverClass: "org.postgresql.Driver" },
  // 达梦 数据库
  "7": { driverClass: "dm.jdbc.driver.DmDriver" },
  // 人大金仓 数据库
  "8": { driverClass: "com.kingbase8.Driver" },
  // 神通 数据库
  "9": { driverClass: "com.oscar.Driver" },
  // SQLite 数据库
  "10": { driverClass: "org.sqlite.JDBC" },
  // DB2 数据库
  "11": { driverClass: "com.ibm.db2.jcc.DB2Driver" },
  // Hsqldb 数据库
  "12": { driverClass: "org.hsqldb.jdbc.JDBCDriver" },
  // Derby 数据库
  "13": { driverClass: "org.apache.derby.jdbc.ClientDriver" },
  // H2 数据库
  "14": { driverClass: "org.h2.Driver" },
  // 其他数据库
  "15": { driverClass: "" }
};
const dbUrlMap = {
  // MySQL 数据库
  "1": { dbUrl: "jdbc:mysql://ip:port/dataBaseName?characterEncoding=UTF-8&useUnicode=true&useSSL=false" },
  //MySQL5.7+ 数据库
  "4": {
    dbUrl:
      "jdbc:mysql://ip:port/dataBaseName?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai"
  },
  // Oracle
  "2": { dbUrl: "jdbc:oracle:thin:@ip:port:ORCL" },
  // SQLServer 数据库
  "3": { dbUrl: "jdbc:sqlserver://ip:port;SelectMethod=cursor;DatabaseName=jeecgboot" },
  // Mariadb 数据库
  "5": { dbUrl: "jdbc:mariadb://ip:port/dataBaseName?characterEncoding=UTF-8&useSSL=false" },
  // Postgresql 数据库
  "6": { dbUrl: "jdbc:postgresql://ip:port/dataBaseName" },
  // 达梦 数据库
  "7": { dbUrl: "jdbc:dm://ip:port/?dataBaseName&zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8" },
  // 人大金仓 数据库
  "8": { dbUrl: "jdbc:kingbase8://ip:port/dataBaseName" },
  // 神通 数据库
  "9": { dbUrl: "jdbc:oscar://192.168.1.125:port/dataBaseName" },
  // SQLite 数据库
  "10": { dbUrl: "jdbc:sqlite://opt/test.db" },
  // DB2 数据库
  "11": { dbUrl: "jdbc:db2://ip:port/dataBaseName" },
  // Hsqldb 数据库
  "12": { dbUrl: "jdbc:hsqldb:hsql://ip/dataBaseName" },
  // Derby 数据库
  "13": { dbUrl: "jdbc:derby://ip:port/dataBaseName" },
  // H2 数据库
  "14": { dbUrl: "jdbc:h2:tcp://ip:port/dataBaseName" },
  // 其他数据库
  "15": { dbUrl: "" }
};
const [registerForm, {
  getFieldsValue,
  resetFields,
  validateFields,
  setFieldsValue,
  validate
}] = useForm({
  labelWidth: 150,
  schemas: [
    {
      field: "id",
      label: "id",
      component: "Input",
      show: false
    },
    {
      field: "dataSourceTypeName",
      label: "id",
      component: "Input",
      show: false
    },
    {
      field: "dataSourceName",
      label: "数据源名称",
      component: "Input",
      required: true
    },
    {
      field: "dataSourceType",
      label: "数据库类型",
      component: "Input",
      required: true,
      slot: "dataSourceType",
      onChange: () => {
        let value = getFieldsValue().dataSourceType;
        if (!value) return;
        value += "";
        setFieldsValue(dbDriverMap[value]);
      }
    },
    {
      field: "driverClass",
      label: "驱动类",
      required: true,
      component: "Input"
    },
    {
      field: "dataBaseName",
      label: "数据库名",
      required: true,
      component: "Input",
      componentProps() {
        return {
          onChange: () => {
            resetUrl();
          }
        };
      }
    },
    {
      field: "ip",
      label: "ip",
      required: true,
      component: "Input",
      componentProps({ formModel }) {
        return {
          onChange: () => {
            resetUrl();
          }
        };
      }
    },
    {
      field: "port",
      label: "端口",
      required: true,
      component: "Input",
      componentProps({ formModel }) {
        return {
          onChange: () => {
            resetUrl();
          }
        };
      }
    },
    {
      field: "url",
      label: "数据源地址",
      required: true,
      component: "Input"
    },
    {
      field: "userName",
      label: "用户名",
      required: true,
      component: "Input"
    },
    {
      field: "password",
      label: "密码",
      required: true,
      component: "InputPassword",
      slot: "pwd"
    },
    {
      field: "remark",
      label: "备注",
      component: "InputTextArea"
    }
  ],
  showActionButtonGroup: false
});

function resetUrl() {
  nextTick(() => {
    let data = getFieldsValue();
    if (!data.dataSourceType) return;
    let url = dbUrlMap[data.dataSourceType].dbUrl;
    if (!url) return;
    url = url.replace("ip", data.ip).replace("port", data.port).replace("dataBaseName", data.dataBaseName);
    setFieldsValue({ url });
  });
}

function handleTest() {
  validate().then(values => {
    setModalProps({ confirmLoading: true });
    testConnection({
      dbType: values.dataSourceType,
      dbDriver: values.driverClass,
      dbUrl: values.url,
      dbUsername: values.userName,
      dbPassword: values.password
    }).then((data) => {
      setModalProps({ confirmLoading: false });

      // if (data.success) {
      //   createMessage.success('连接成功');
      // }
    }).catch(e => {
      setModalProps({ confirmLoading: false });
    });
  });
}

function setData(id) {
  if (id) {
    defHttp.get({ url: "/cwqs/cwqsDataSource/queryById", params: { id } }, { joinParamsToUrl: true }).then(data => {
      // console.log(data);
      openModal();
      nextTick(() => {
        setFieldsValue(data)
      });
    });
  } else {
    openModal();
    nextTick(() => {resetFields()});
  }
}

const Api = {
  edit: "/cwqs/cwqsDataSource/edit",
  add: "/cwqs/cwqsDataSource/add"
};

function handleSubmit() {
  setModalProps({ confirmLoading: true });
  validate().then(data => {
    setModalProps({ confirmLoading: false });
    defHttp.post({ url: data.id ? Api.edit : Api.add, data }).then(data => {
      closeModal();
      emits("ok");
    });
  }).catch(e => {
    setModalProps({ confirmLoading: false });
  });
}

defineExpose({
  setData
});
</script>
